package test05block;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Deadlock {
    public static String str1 = "str1";
    public static String str2 = "str2";

    public class Block {
        //练习八：死锁回顾
        public static void main(String[] args) {
            //创建一个线程池
            ExecutorService executorService = Executors.newFixedThreadPool(2);
            //使用lambda表达式提交一个线程
            executorService.submit(() -> {
                try {
                    while (true) {
                        synchronized (Deadlock.str1) {
                            System.out.println(Thread.currentThread().getName() + "锁住 str1");
                            Thread.sleep(1000);
                            synchronized (Deadlock.str2) {
                                System.out.println(Thread.currentThread().getName() + "锁住 str2");
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            //使用lambda表达式提交一个线程
            executorService.submit(() -> {
                try {
                    while (true) {
                        synchronized (Deadlock.str2) {
                            System.out.println(Thread.currentThread().getName() + "锁住 str2");
                            Thread.sleep(1000);
                            synchronized (Deadlock.str1) {
                                System.out.println(Thread.currentThread().getName() + "锁住 str1");
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            // 关闭线程池
            executorService.shutdown();
        }
    }
}



